package com.youlu.campus.web.group.service.impl;

import com.youlu.campus.base.base.ConstantsEnum;
import com.youlu.campus.base.base.PageQueryRequest;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.group.enums.GroupStatusEnum;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.common.base.delay.DelayQueueRequest;
import com.youlu.campus.web.common.base.delay.DelayQueueServiceSceneEnum;
import com.youlu.campus.web.group.dto.request.CreateGroupRequest;
import com.youlu.campus.web.group.dto.request.GroupMemberRequest;
import com.youlu.campus.web.group.dto.request.GroupQuitRequest;
import com.youlu.campus.web.group.dto.request.UniversityGroupRequest;
import com.youlu.campus.web.group.dto.response.GroupBaseResponse;
import com.youlu.campus.web.group.dto.response.GroupHomeResponse;
import com.youlu.campus.web.group.dto.response.GroupMemberResponse;
import com.youlu.campus.web.group.dto.response.GroupResponse;
import com.youlu.campus.web.group.entity.GroupLogPO;
import com.youlu.campus.web.group.entity.GroupMemberPO;
import com.youlu.campus.web.group.entity.GroupPO;
import com.youlu.campus.web.group.service.GroupService;
import com.youlu.campus.service.invite.UserInviteService;
import com.youlu.campus.web.sign.entity.SignPlanDailyPO;
import com.youlu.campus.web.university.entity.UniversityPO;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.web.common.utils.DateContainer;
import com.youlu.campus.web.common.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zgz
 * @date 2020/11/10 17:24
 */
@Slf4j
@Service
public class GroupServiceImpl extends BaseService implements GroupService {

    @Value("${sys.universityGroupMaxCount}")
    private Integer UNIVERSITY_GROUP_MAX_COUNT;

    @Value("${sys.memberCountMin}")
    private Integer MEMBER_COUNT_MIN;

//    @Autowired
//    private MQService mqService;

    @Autowired
    private UserInviteService userInviteService;

    @Override
    public String createGroup(CreateGroupRequest request) {
        UserPO user = RequestContext.getCurUser();
        log.info("createGroup request {} userId {}", request, user.getId());
        //判断小组名称是否重复
        if (isDuplicateName(request.getName(), null)) {
            throw new BusinessException("创建小组失败，小组名称重复~");
        }
        //判断所在大学小组数量是否超过100个
        Query query = new Query();
        query.addCriteria(Criteria.where("universityValue").is(user.getUniversityValue()));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        if (mongoTemplate.count(query, GroupPO.class) >= UNIVERSITY_GROUP_MAX_COUNT) {
            throw new BusinessException("创建小组失败，学校小组数量过多~");
        }
        //判断是否建立过小组
        query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(user.getId()));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        if (mongoTemplate.exists(query, GroupPO.class)) {
            throw new BusinessException("创建小组失败，你已经建立过小组~");
        }
        GroupPO groupPO = new GroupPO();
        BeanUtils.copyProperties(request, groupPO);
        groupPO.setUser(super.getUserInfo(user));
        groupPO.setId(null);
        groupPO.setMembersCount(1);
        groupPO.setCreatedTime(new Date());
        groupPO.setUpdatedTime(new Date());
        groupPO.setProbationEndDate(DateTimeUtils.add(new Date(), 24, Calendar.HOUR));
        groupPO.setStatus(GroupStatusEnum.PROBATION.getValue());
        groupPO.setUniversityValue(user.getUniversityValue());
        groupPO.setUniversityName(user.getUniversityName());
        mongoTemplate.save(groupPO);
        //加入成员列表
        GroupMemberPO groupMemberPO = new GroupMemberPO();
        groupMemberPO.setUser(super.getUserInfo(user));
        groupMemberPO.setGroupId(groupPO.getId());
        groupMemberPO.setGroupName(groupPO.getName());
        groupMemberPO.setCreator(true);
        groupMemberPO.setCreatedTime(new Date());
        groupMemberPO.setUpdatedTime(new Date());
        mongoTemplate.save(groupMemberPO);
        //加入延迟队列
        DelayQueueRequest delayQueueRequest = new DelayQueueRequest();
        delayQueueRequest.setScene(DelayQueueServiceSceneEnum.CREATE_GROUP.getScene());
        delayQueueRequest.setContent(groupPO.getId());
//        mqService.sendDelayQueue(24 * 60, delayQueueRequest);
        return groupPO.getId();
    }

    @Override
    public String editGroup(CreateGroupRequest request) {
        UserPO user = RequestContext.getCurUser();
        log.info("editGroup request {} userId {}", request, user.getId());
        if (StringUtils.isBlank(request.getGroupId())) {
            throw new BusinessException("Id 为空~");
        }
        //判断小组名称是否重复
        if (isDuplicateName(request.getName(), request.getGroupId())) {
            throw new BusinessException("编辑小组失败，小组名称重复~");
        }
        GroupPO groupPO = mongoTemplate.findById(request.getGroupId(), GroupPO.class);
        if (groupPO == null || !user.getId().equals(groupPO.getUser().getUserId())) {
            throw new BusinessException("无权修改~");
        }
        BeanUtils.copyProperties(request, groupPO);
        groupPO.setUpdatedTime(new Date());
        mongoTemplate.save(groupPO);
        return ConstantsEnum.ResultStatus.SUCCESS.getCode();
    }

    @Override
    public GroupHomeResponse getGroupHomeInfo(String groupId) {
        String userId = RequestContext.getUserId();
        log.info("getGroupHomeInfo userId {} groupId {}", userId, groupId);
        GroupPO groupPO = mongoTemplate.findById(groupId, GroupPO.class);
        if (groupPO == null) {
            throw new BusinessException("未查询到小组信息");
        }
        if (groupPO.getStatus().equals(GroupStatusEnum.DISSOLUTION.getValue())) {
            throw new BusinessException("小组已解散");
        }
        if (groupPO.getStatus().equals(GroupStatusEnum.PROBATION.getValue())) {
            if (groupPO.getProbationEndDate().before(new Date()) && groupPO.getMembersCount() < MEMBER_COUNT_MIN) {
                groupPO.setStatus(GroupStatusEnum.DISSOLUTION.getValue());
                groupPO.setDissolutionReason("未完成任务强制解散");
                groupPO.setDeleted(true);
                groupPO.setUpdatedTime(new Date());
                mongoTemplate.save(groupPO);
                //小组成员设置成无效
                this.removeGroupMembers(groupId);
                //日志
                GroupLogPO logPO = new GroupLogPO();
                logPO.setUserId(groupPO.getUser().getUserId());
                logPO.setGroupId(groupPO.getId());
                logPO.setReason("未达到成员人数解散");
                logPO.setType("dissolution");
                logPO.setCreatedTime(new Date());
                mongoTemplate.save(logPO);
                throw new BusinessException("小组已解散");
            }
            if (groupPO.getProbationEndDate().after(new Date()) && groupPO.getMembersCount() >= MEMBER_COUNT_MIN) {
                groupPO.setStatus(GroupStatusEnum.NORMAL.getValue());
                groupPO.setFinishTaskDate(new Date());
                groupPO.setUpdatedTime(new Date());
                mongoTemplate.save(groupPO);
            }
        }
        GroupHomeResponse response = new GroupHomeResponse();
        BeanUtils.copyProperties(groupPO, response);
        //获取学校信息
        Query uquery = new Query();
        uquery.addCriteria(Criteria.where("value").is(groupPO.getUniversityValue()));
        UniversityPO universityPO = mongoTemplate.findOne(uquery, UniversityPO.class);
        if (universityPO != null) {
            response.setUniversityName(universityPO.getName());
            response.setUniversityLogo(universityPO.getLogo());
        }
        //判断是否是管理员
        response.setManager(userId.equals(groupPO.getUser().getUserId()));
        //判断是否已经加入组织
        Query query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("groupId").is(groupId));
        query.addCriteria(Criteria.where("deleted").is(false));
        response.setJoin(mongoTemplate.exists(query, GroupMemberPO.class));
        //判断今天是否已经打卡
//        //TODO
//        //获取大学内排名
//        query = new Query();
//        query.addCriteria(Criteria.where("deleted").is(false));
//        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
//        query.addCriteria(Criteria.where("activeValue").gt(groupPO.getActiveValue()));
//        long gCount = mongoTemplate.count(query, GroupPO.class);
//        query = new Query();
//        query.addCriteria(Criteria.where("deleted").is(false));
//        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
//        query.addCriteria(Criteria.where("activeValue").is(groupPO.getActiveValue()));
//        long eCount = mongoTemplate.count(query, GroupPO.class);
//        response.setRanking(gCount + eCount + 1L);
        response.setRanking(getGroupRankById(groupId));
        return response;
    }

    @Override
    public Page<GroupMemberResponse> getGroupMembers(GroupMemberRequest request) {
        String userId = RequestContext.getUserId();
        log.info("getGroupMembers userId {} request {}", userId, request);
        Query query = new Query();
        query.addCriteria(Criteria.where("groupId").is(request.getGroupId()));
        query.addCriteria(Criteria.where("deleted").is(false));
        long count = mongoTemplate.count(query, GroupMemberPO.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.ASC, "id"));
        Sort sort=Sort.by(Sort.Direction.ASC, "id");
        query.with(sort);
        List<GroupMemberPO> groupMemberPOList = mongoTemplate.find(query.with(pageRequest), GroupMemberPO.class);
        List<GroupMemberResponse> list = groupMemberPOList.stream().map(groupMemberPO -> {
            GroupMemberResponse response = new GroupMemberResponse();
            BeanUtils.copyProperties(groupMemberPO, response);
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public String joinGroup(String groupId) {
        UserPO user = RequestContext.getCurUser();
        log.info("joinGroup groupId {} userId {}", groupId, user.getId());
        GroupPO groupPO = mongoTemplate.findById(groupId, GroupPO.class);
        if (groupPO == null || groupPO.getStatus().equals(GroupStatusEnum.DISSOLUTION.getValue())) {
            throw new BusinessException("小组不存在或已解散~");
        }
        //判断我是否已经加入了组织
        if (isJoinGroup(user.getId())) {
            throw new BusinessException("你已经加入了一个组织，不要重复加入~");
        }
        GroupMemberPO groupMemberPO = new GroupMemberPO();
        groupMemberPO.setUser(super.getUserInfo(user));
        groupMemberPO.setGroupId(groupId);
        groupMemberPO.setGroupName(groupPO.getName());
        groupMemberPO.setCreatedTime(new Date());
        groupMemberPO.setUpdatedTime(new Date());
        mongoTemplate.save(groupMemberPO);
        //成员数量+1
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(groupId));
        Update update = new Update();
        update.set("updatedTime", new Date());
        update.inc("membersCount");
        if (groupPO.getMembersCount() + 1 > MEMBER_COUNT_MIN) {
            update.set("finishTaskDate", new Date());
            update.set("status", GroupStatusEnum.NORMAL.getValue());
        }
        mongoTemplate.updateFirst(query, update, GroupPO.class);
        //处理邀请人
//        userInviteService.handleJoinGroupUserInvite(groupId, user.getId());
        //日志
        GroupLogPO logPO = new GroupLogPO();
        logPO.setUserId(user.getId());
        logPO.setGroupId(groupId);
        logPO.setType("join");
        logPO.setCreatedTime(new Date());
        mongoTemplate.save(logPO);
        return ConstantsEnum.ResultStatus.SUCCESS.getCode();
    }

    @Override
    public String quitGroup(GroupQuitRequest request) {
        UserPO user = RequestContext.getCurUser();
        log.info("quitGroup request {} userId {}", request, user.getId());
        //判断我是否已经加入了组织
        Query query = new Query();
        query.addCriteria(Criteria.where("groupId").is(request.getGroupId()));
        query.addCriteria(Criteria.where("user.userId").is(user.getId()));
        query.addCriteria(Criteria.where("deleted").is(false));
        if (!mongoTemplate.exists(query, GroupMemberPO.class)) {
            throw new BusinessException("你已经退出了该小组~");
        }
        Update update = new Update();
        update.set("updatedTime", new Date());
        update.set("deleted", true);
        mongoTemplate.updateFirst(query, update, GroupMemberPO.class);
        query = new Query();
        query.addCriteria(Criteria.where("id").is(request.getGroupId()));
        update = new Update();
        update.set("updatedTime", new Date());
        update.inc("membersCount", -1);
        mongoTemplate.updateFirst(query, update, GroupPO.class);
        //日志
        GroupLogPO logPO = new GroupLogPO();
        logPO.setUserId(user.getId());
        BeanUtils.copyProperties(request, logPO);
        logPO.setType("quit");
        logPO.setCreatedTime(new Date());
        mongoTemplate.save(logPO);
        return ConstantsEnum.ResultStatus.SUCCESS.getCode();
    }

    @Override
    public void handleGroupProbation(String groupId) {
        log.info("handleGroupProbation groupId {}", groupId);
        GroupPO groupPO = mongoTemplate.findById(groupId, GroupPO.class);
        if (groupPO == null || !groupPO.getStatus().equals(GroupStatusEnum.PROBATION.getValue())) {
            return;
        }
        if (groupPO.getMembersCount() < MEMBER_COUNT_MIN) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(groupId));
            query.addCriteria(Criteria.where("status").is(GroupStatusEnum.PROBATION.getValue()));
            Update update = new Update();
            update.set("updatedTime", new Date());
            update.set("deleted", true);
            update.set("status", GroupStatusEnum.DISSOLUTION.getValue());
            mongoTemplate.updateFirst(query, update, GroupPO.class);
            //小组成员设置成无效
            this.removeGroupMembers(groupId);
            //日志
            GroupLogPO logPO = new GroupLogPO();
            logPO.setUserId(groupPO.getUser().getUserId());
            logPO.setGroupId(groupPO.getId());
            logPO.setReason("未达到成员人数解散");
            logPO.setType("dissolution");
            logPO.setCreatedTime(new Date());
            mongoTemplate.save(logPO);
        }
        if (groupPO.getMembersCount() >= MEMBER_COUNT_MIN) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(groupId));
            query.addCriteria(Criteria.where("status").is(GroupStatusEnum.PROBATION.getValue()));
            Update update = new Update();
            update.set("updatedTime", new Date());
            update.set("status", GroupStatusEnum.NORMAL.getValue());
            update.set("finishTaskDate", new Date());
            mongoTemplate.updateFirst(query, update, GroupPO.class);
        }
    }

    @Override
    public Page<GroupResponse> getUniversityGroups(UniversityGroupRequest request) {
        String userId = RequestContext.getUserId();
        log.info("getUniversityGroups userId {} request {}", userId, request);
        Query query = new Query();
        query.addCriteria(Criteria.where("universityValue").is(request.getUniversityValue()));
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        long count = mongoTemplate.count(query, GroupPO.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "membersCount"));
        Sort sort=Sort.by(Sort.Direction.DESC, "membersCount");
        query.with(sort);
        List<GroupPO> groupPOList = mongoTemplate.find(query.with(pageRequest), GroupPO.class);
        List<GroupResponse> list = groupPOList.stream().map(groupPO -> {
            GroupResponse response = new GroupResponse();
            BeanUtils.copyProperties(groupPO, response);
            response.setGroupId(groupPO.getId());
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    private boolean isDuplicateName(String name, String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        query.addCriteria(Criteria.where("deleted").is(false));
        if (StringUtils.isNotBlank(id)) {
            query.addCriteria(Criteria.where("id").ne(id));
        }
        return mongoTemplate.exists(query, GroupPO.class);
    }

    private void removeGroupMembers(String groupId) {
        //小组成员设置成无效
        Query query = new Query();
        query.addCriteria(Criteria.where("groupId").is(groupId));
        query.addCriteria(Criteria.where("deleted").is(false));
        Update update = new Update();
        update.set("updatedTime", new Date());
        update.set("deleted", true);
        mongoTemplate.updateMulti(query, update, GroupMemberPO.class);
    }

    @Override
    public boolean isJoinGroup(String userId) {
        //判断我是否已经加入了组织
        Query query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        if (mongoTemplate.exists(query, GroupMemberPO.class)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isGroupLeader(String groupId,String userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(groupId));
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        query.addCriteria(Criteria.where("deleted").is(false));
        return mongoTemplate.exists(query, GroupPO.class);
    }

    @Override
    public GroupPO getJoinGroup(String userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        GroupMemberPO memberPO = mongoTemplate.findOne(query, GroupMemberPO.class);
        if (memberPO != null) {
            GroupPO groupPO = mongoTemplate.findById(memberPO.getGroupId(), GroupPO.class);
            if (groupPO != null && !groupPO.getDeleted() && !groupPO.getStatus().equals(GroupStatusEnum.DISSOLUTION.getValue())) {
                return groupPO;
            }
        }
        return null;
    }

    @Override
    public String getJoinGroupId(String userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        GroupMemberPO memberPO = mongoTemplate.findOne(query, GroupMemberPO.class);
        if (memberPO != null) {
            return memberPO.getGroupId();
        }
        return null;
    }

    @Override
    public GroupResponse getMyJoinGroup() {
        String userId = RequestContext.getUserId();
        log.info("getMyJoinGroup userId {}", userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("user.userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        GroupMemberPO memberPO = mongoTemplate.findOne(query, GroupMemberPO.class);
        if (memberPO != null) {
            GroupPO groupPO = mongoTemplate.findById(memberPO.getGroupId(), GroupPO.class);
            if (groupPO != null && !groupPO.getDeleted() && !groupPO.getStatus().equals(GroupStatusEnum.DISSOLUTION.getValue())) {
                GroupResponse response = new GroupResponse();
                BeanUtils.copyProperties(groupPO, response);
                response.setGroupId(groupPO.getId());
                response.setCreator(memberPO.isCreator());
                return response;
            }
        }
        return null;
    }

    @Override
    public Long getUniversityGroupCount(String universityValue) {
        log.info("getUniversityGroupCount universityValue {}", universityValue);
        Query query = new Query();
        query.addCriteria(Criteria.where("universityValue").is(universityValue));
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        return mongoTemplate.count(query, GroupPO.class);
    }

    @Override
    public Page<GroupResponse> getGroupRank(PageQueryRequest request) {
        String userId = RequestContext.getUserId();
        log.info("getGroupRank userId {} request {}", userId, request);
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        long count = mongoTemplate.count(query, GroupPO.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "activeValue"));
        Sort sort=Sort.by(Sort.Direction.DESC, "activeValue");
        query.with(sort);
        int rank = (request.getPage()-1)*request.getPageSize();
        List<GroupResponse> list = new ArrayList<>();
        List<GroupPO> groupPOList = mongoTemplate.find(query.with(pageRequest), GroupPO.class);
        for (GroupPO group :groupPOList) {
            rank ++ ;
            GroupResponse response = mapperFacade.map(group,GroupResponse.class);
            response.setGroupId(group.getId());
            response.setCreator(group.getUser().getUserId().equals(userId));
            response.setRank(rank);
            list.add(response);
        }
        GroupResponse my = this.getMyGroupRank(userId);
        if (my != null && request.getPage() == 1) {
            list.add(0, my);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }


    @Override
    public GroupResponse getMyGroupRank() {
        String userId = RequestContext.getUserId();
        GroupResponse my = this.getMyGroupRank(userId);
        return my;
    }

    @Override
    public void handleGroupActiveValue() {
        log.info("handleGroupActiveValue start");
        //获取组织
        Integer page = 1;
        Integer pageSize = 1000;
        Query query = new Query();
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        query.addCriteria(Criteria.where("deleted").is(false));
        DateContainer dateContainer = DateTimeUtils.getYesterdayStartEndTime();
        List<String> universityValues = new ArrayList<>();
        while (true) {
            PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
            query.with(pageRequest);
            List<GroupPO> groupPOS = mongoTemplate.find(query, GroupPO.class);
            if (CollectionUtils.isEmpty(groupPOS)) {
                break;
            }
            for (GroupPO groupPO : groupPOS) {
                Long activeValue = 0L;
                //获取新增成员数
                Query mQuery = new Query();
                mQuery.addCriteria(Criteria.where("groupId").is(groupPO.getId()));
                mQuery.addCriteria(Criteria.where("deleted").is(false));
                mQuery.addCriteria(Criteria.where("createdTime").gte(dateContainer.getStartTime()).lte(dateContainer.getEndTime()));
                Long newMemberCount = mongoTemplate.count(mQuery, GroupMemberPO.class);
                activeValue += newMemberCount * 3;
                Long newSignCount = mongoTemplate.count(mQuery, SignPlanDailyPO.class);
                activeValue += newSignCount;
                Query gQuery = new Query();
                gQuery.addCriteria(Criteria.where("id").is(groupPO.getId()));
                Update update = new Update();
                update.set("updatedTime", new Date());
                update.set("activeValue", activeValue.intValue());
                mongoTemplate.updateFirst(gQuery, update, GroupPO.class);
                //大学活力值
                Query uQuery = new Query();
                uQuery.addCriteria(Criteria.where("value").is(groupPO.getUniversityValue()));
                update = new Update();
                update.set("updatedTime", new Date());
                if (!universityValues.contains(groupPO.getUniversityValue())) {
                    update.set("activeValue", activeValue.intValue());
                } else {
                    update.inc("activeValue", activeValue.intValue());
                }
                mongoTemplate.updateFirst(uQuery, update, UniversityPO.class);
                universityValues.add(groupPO.getUniversityValue());
            }
            page++;
        }
    }

    private GroupResponse getMyGroupRank(String userId) {
        GroupPO groupPO = this.getJoinGroup(userId);
        if (groupPO == null) {
            return null;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        PageRequest pageRequest = PageRequest.of(0, 500);
//        query.with(new Sort(Sort.Direction.DESC, "activeValue"));
        Sort sort=Sort.by(Sort.Direction.DESC, "activeValue");
        query.with(sort);
        List<GroupPO> groupPOList = mongoTemplate.find(query.with(pageRequest), GroupPO.class);
        for (int i = 0; i < groupPOList.size(); i++) {
            GroupPO group = groupPOList.get(i);
            if (group.getId().equals(groupPO.getId())) {
                GroupResponse response = new GroupResponse();
                BeanUtils.copyProperties(groupPO, response);
                response.setGroupId(groupPO.getId());
                response.setRank(i + 1);
                response.setTop(true);
                response.setCreator(groupPO.getUser().getUserId().equals(userId));
                return response;
            }
        }
        return null;
    }

    private Integer getGroupRankById(String groupId){
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").ne(GroupStatusEnum.DISSOLUTION.getValue()));
        PageRequest pageRequest = PageRequest.of(0, 500);
//        query.with(new Sort(Sort.Direction.DESC, "activeValue"));
        Sort sort=Sort.by(Sort.Direction.DESC, "activeValue");
        query.with(sort);
        List<GroupPO> groupPOList = mongoTemplate.find(query.with(pageRequest), GroupPO.class);
        for (int i = 0; i < groupPOList.size(); i++) {
            GroupPO group = groupPOList.get(i);
            if (group.getId().equals(groupId)) {
                return i+1;
            }
        }
        return null;
    }

    @Override
    public GroupBaseResponse getGroupDissolutionPopup() {
        String userId = RequestContext.getUserId();
        log.info("getGroupDissolutionPopup userId {}", userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("read").is(false));
        query.addCriteria(Criteria.where("type").is("dissolution"));
        GroupLogPO logPO = mongoTemplate.findOne(query, GroupLogPO.class);
        if (logPO != null) {
            GroupPO groupPO = mongoTemplate.findById(logPO.getGroupId(), GroupPO.class);
            if (groupPO != null) {
                //标记为已读
                logPO.setRead(true);
                mongoTemplate.save(logPO);

                GroupBaseResponse response = new GroupBaseResponse();
                BeanUtils.copyProperties(groupPO, response);
                return response;
            }
        }
        return null;
    }

}
